/**
 * fileName: YLES_UI_FORM
 * @NApiVersion 2.1
 */
import ui, {FieldBreakType, Form, Field} from 'N/ui/serverWidget'
import log = require("N/log");
import search = require("N/search");
import file = require("N/file");
import {CustomRecordType} from "./YLES_RELATED_RECORDTYPE";
import {ObjectJson} from "./YLES_SEARCH_TOOL";
import {LookupValueObject} from "N/search";

//用于定义页面字段
type FS_IsMandatory = true | false

interface Btn {
    id: string
    label: string
    functionName: string
}

interface Group {
    id: string
    label: string
}

interface CUSTField {
    id: string
    label: string
    type: ui.FieldType
    source?: string
    displayType?: ui.FieldDisplayType
    isMandatory?: FS_IsMandatory
    container?: string
    width?: number
    height?: number
    breakType?: FieldBreakType
    ignoreDl?: boolean
    dlName?: string
}

interface tabOptions {
    /** An internal ID for the field group. */
    id: string;
    /** The label for this field group. */
    label: string;
    /** The internal ID of the tab to add the field group to. By default, the field group is added to the main section of the form. */
    tab?: string;
}

export interface UI_Form {
    title: string
    btn: Btn[]
    group: Group[]
    bodyField: CUSTField[]
    lineField: CUSTField[]
    sublistInfo?: any
    tab?: tabOptions[]
}

export interface CustomSource {
    value: string
    text: string
}

//创建Get界面的Form
/**
 *
 * @param UI_GET_INFO - 封装的Form信息
 * @param sublistType - 创建的子列表的类型 ，默认为LIST
 * @param needMarkBtn - 是否需要添加markAll按钮，默认添加
 * @param hideNavBar - Form 是否需要隐藏NS菜单
 */
export function createUI(UI_GET_INFO: UI_Form, sublistType: ui.SublistType | null = ui.SublistType.LIST, needMarkBtn: boolean = true, hideNavBar: boolean = false): Form {
    const form = ui.createForm({title: UI_GET_INFO.title, hideNavBar: hideNavBar});
    //btn
    for (const bv of UI_GET_INFO.btn) {
        form.addButton(bv);
    }

    //group
    for (const gv of UI_GET_INFO.group) {
        form.addFieldGroup(gv);
    }

    //tab
    if (UI_GET_INFO.tab) {
        for (const tv of UI_GET_INFO.tab) {
            form.addFieldGroup(tv);
        }
    }

    //body field
    for (const bfv of UI_GET_INFO.bodyField) {
        form.addField(bfv);

        if (bfv.isMandatory) form.getField({id: bfv.id}).isMandatory = bfv.isMandatory;
        if (bfv.displayType) {
            form.getField({id: bfv.id}).updateDisplayType({displayType: bfv.displayType});
        }
        if (bfv.breakType) {
            form.getField({id: bfv.id}).updateBreakType({breakType: bfv.breakType});
        }
    }

    //line field
    if (sublistType && UI_GET_INFO.lineField.length > 0) {
        const sublist = form.addSublist({id: 'info_list', label: 'Results', type: sublistType});
        for (const lfv of UI_GET_INFO.lineField) {
            sublist.addField(lfv);

            if (lfv.displayType) {
                sublist.getField({id: lfv.id}).updateDisplayType({displayType: lfv.displayType});
            }
        }

        //mark all button
        if (needMarkBtn) {
            sublist.addButton({id: 'mark_all', label: 'Mark All', functionName: 'markAll(true)'});
            sublist.addButton({id: 'unmark_all', label: 'Unmark All', functionName: 'markAll(false)'});
            sublist.addButton({id: 'mark100', label: 'Mark 100', functionName: 'markAll(true,100)'});
        }
        if (form.getField({id: 'lines_page'})) {
            addCustomSource(form.getField({id: 'lines_page'}), ['10', '50', '100', '200', '500', '1000']);
        }
    }

    //more sublist
    if (UI_GET_INFO.sublistInfo) {
        //添加多个sublist
        for (const sl of UI_GET_INFO.sublistInfo.sublist) {
            const sublist = form.addSublist({id: sl.id, label: sl.label, type: sl.type,tab:sl.tab});

            //每个sublist的字段
            for (const slf of UI_GET_INFO.sublistInfo[sl.id]) {
                sublist.addField(slf);

                if (slf.displayType) {
                    sublist.getField({id: slf.id}).updateDisplayType({displayType: slf.displayType});
                }
            }
        }
    }

    return form;
}

//添加自定义select source
function addCustomSource(f: Field, source: CustomSource[] | string[]) {
    for (const d of source) {
        if (typeof d === 'string') {
            f.addSelectOption({value: d, text: d});
        } else {
            f.addSelectOption(d);
        }
    }
}

//获取导入信息
function getImportLogInfo(logId: number) {
    const columns = ['custrecord_yles_csv_name', 'custrecord_yles_status', 'custrecord_yles_start_time', 'custrecord_yles_end_time',
        'custrecord_yles_csvfile','custrecord_yles_ck_error_csv','custrecord_yles_imp_error_csv','custrecord_yles_imp_csv_line_no',
        'custrecord_yles_total_csv_line_no','custrecord_yles_ckd_line_no'];
    const res = search.lookupFields({type: CustomRecordType().IMPORT_ITEM_BARCODE_LOG, id: logId, columns: columns});
    const logInfo: ObjectJson = {};
    log.debug('res',res);
    logInfo.fileName = res[columns[0]] as string;
    logInfo.state = ((res[columns[1]] as LookupValueObject [])[0] || {}).text as string;
    logInfo.stateid = ((res[columns[1]] as LookupValueObject [])[0] || {}).value as string;
    logInfo.created = res[columns[2]] as string;
    logInfo.completedTime = res[columns[3]] as string;
    logInfo.csvFile = ((res[columns[4]] as LookupValueObject [])[0] || {}).value as string;
    logInfo.ckErrorFile = ((res[columns[5]] as LookupValueObject [])[0] || {}).value as string;
    logInfo.impErrorFile = ((res[columns[6]] as LookupValueObject [])[0] || {}).value as string;
    logInfo.ckSuccessLine = res[columns[7]] as string;
    logInfo.totalLine = res[columns[8]] as string;
    logInfo.ckdLine = res[columns[9]] as string;
    return logInfo;
}

//创建导入历史界面
export function createImportResultForm(logId: number,irForm:Form) {
    const importLogInfo = getImportLogInfo(logId);
    log.debug('importLogInfo',importLogInfo)
    irForm.addFieldGroup({id:'result_group',label:'Result'});

    let ff = irForm.addField({id: 'file', label: 'Imported CSV File', type: 'inlinehtml',container:'result_group'});
    ff.updateDisplayType({displayType: 'inline'});
    // ff.defaultValue = importLogInfo.csvFile as string;
    ff.defaultValue = spellFileHtml('file','Imported CSV File',importLogInfo.csvFile as string,importLogInfo.fileName as string);
    let cf = irForm.addField({id: 'created', label: 'Created Time', type: 'text',container:'result_group'});
    cf.updateDisplayType({displayType: 'inline'});
    cf.defaultValue = importLogInfo.created as string;
    let cdf = irForm.addField({id: 'completed_time', label: 'Completed Time', type: 'text',container:'result_group'});
    cdf.updateDisplayType({displayType: 'inline'});
    cdf.defaultValue = importLogInfo.completedTime as string;
    let sf = irForm.addField({id: 'state', label: 'Status', type: 'text',container:'result_group'});
    sf.updateDisplayType({displayType: 'inline'});
    sf.defaultValue = importLogInfo.state as string;
    let lgf = irForm.addField({id: 'import_log_id', label: 'Log', type: 'text',container:'result_group'});
    lgf.updateDisplayType({displayType: 'hidden'});
    lgf.defaultValue = String(logId);
    let csf = irForm.addField({id: 'ck_success_line', label: 'Check Success Line', type: 'text',container:'result_group'});
    csf.updateDisplayType({displayType: 'hidden'});
    csf.defaultValue = String(importLogInfo.ckSuccessLine || '');

    //添加报错文件
    let cef = irForm.addField({id: 'ck_error_file', label: 'Check Error File', type: 'inlinehtml',container:'result_group'});
    cef.updateDisplayType({displayType: 'inline'});
    // cef.defaultValue = importLogInfo.ckErrorFile as string;
    cef.defaultValue = spellFileHtml('ck_error_file','Check Error File',importLogInfo.ckErrorFile as string,'Check Error File');
    let ief = irForm.addField({id: 'imp_error_file', label: 'Import Error File', type: 'inlinehtml',container:'result_group'});
    ief.updateDisplayType({displayType: 'inline'});
    // ief.defaultValue = importLogInfo.impErrorFile as string;
    ief.defaultValue = spellFileHtml('imp_error_file','Import Error File',importLogInfo.impErrorFile as string,'Import Error File');

    //导入进度条
    if (importLogInfo.stateid == '3') {
        let ipf = irForm.addField({id: 'progress', label: 'progress', type: 'inlinehtml',container:'result_group'});
        ipf.updateDisplayType({displayType: 'inline'});
        ipf.defaultValue = `
                <div><br/><br/><br/><br/><br/><table>
                <tr><td style="font-size: 15px">Import Progress： &nbsp;</td></tr>
                <tr><td><div style="width: 450px" id="import_csv_progress" data-init="true"></div></td></tr>
                </table></div>
            `;

        addExternalJS(irForm);
    }
    //校验进度
    else if (importLogInfo.stateid == '2') {
        irForm.title = 'Check Item&Barcode';
        let tsf = irForm.addField({id: 'total_line', label: 'Total Line', type: 'text',container:'result_group'});
        tsf.updateDisplayType({displayType: 'hidden'});
        tsf.defaultValue = String(importLogInfo.totalLine || '');
        let tff = irForm.addField({id: 'ckd_line', label: 'Checked Line', type: 'text',container:'result_group'});
        tff.updateDisplayType({displayType: 'hidden'});
        tff.defaultValue = String(importLogInfo.ckdLine || '');

        let ipf = irForm.addField({id: 'progress', label: 'progress', type: 'inlinehtml',container:'result_group'});
        ipf.updateDisplayType({displayType: 'inline'});
        ipf.defaultValue = `
                <div><br/><br/><br/><br/><br/><table>
                <tr><td style="font-size: 15px">Check Progress： &nbsp;</td></tr>
                <tr><td><div style="width: 450px" id="check_csv_progress" data-init="true"></div></td></tr>
                </table></div>
            `;

        addExternalJS(irForm);
    }

    irForm.addButton({id: 'refresh', label: 'Refresh', functionName: 'refresh'});
}

//添加外部js
function addExternalJS(form:Form) {
    const js_file_obj = file.load({id: './jquery.lineProgressbar.js'});
    const js_str = js_file_obj.getContents();

    const css_file_obj = file.load({id: './jquery.lineProgressbar.css'});
    const css_str = css_file_obj.getContents();
    try {
        const tmpHtmlVal = `<script>
                    try{
                        ${js_str}
                    }catch (ex) {
                        console.log('addExternalJS error',ex);
                    };
                </script>

                <style type="text/css">
                    ${css_str}
                </style>`;
        form.addField({
            type : 'inlinehtml',
            label : ' &nbsp; ',
            id : 'custpage__add_external_js'
        }).defaultValue = tmpHtmlVal;
    } catch (ex) {
        log.error({
            title : 'addExternalJS error',
            details : ex
        });
    }
}

//拼写file的html代码
function spellFileHtml(fid?:string,fName?:string,fileId?:number | null | string,fileName?:string) {
    if(fileId) {
        return `<div class="uir-field-wrapper" data-field-type="select">
        <span id="${fid}_fs_lbl_uir_label" class="smallgraytextnolink uir-label ">
        <span id="${fid}_fs_lbl" class="smallgraytextnolink" style="">
        <a tabindex="-1" title="What's this?" style="cursor:help" class="smallgraytextnolink">${fName}</a>
        </span></span><span class="uir-field inputreadonly">
        <a class="smalltext" href="#" style="text-decoration: none;" onclick="previewMedia(${fileId},false,true); return false" onmouseover="this.style.textDecoration='underline'; window.status='preview file'; return true;" onmouseout="this.style.textDecoration='none'; window.status='';">preview ${fileName}</a>&nbsp;&nbsp;
        <a href="#" onclick="previewMedia(${fileId},false,true); return false" class="smalltext">download</a>&nbsp;&nbsp;<a href="#" onclick="nlOpenWindow('/app/common/record/edittextmediaitem.nl?id=${fileId}&amp;e=T&amp;l=T&amp;target=filesize', 'edittextmediaitem${fileId}', 700, 880); return false" class="smalltext">Edit</a>
        </span>
    </div>`;
    }
    return `<div class="uir-field-wrapper" data-field-type="select"><span id="${fid}_fs_lbl_uir_label" class="smallgraytextnolink uir-label ">
            <span id="${fid}_fs_lbl" class="smallgraytextnolink" style="">
            <a tabindex="-1" title="What's this?" style="cursor:help" class="smallgraytextnolink">${fName}</a>
            </span></span><span class="uir-field inputreadonly">
            </span>
            </div>`;
}